package com.android.nodejs.livejs.adapters;

import java.util.List;

import com.android.nodejs.livejs.R;
import com.android.nodejs.livejs.models.Chat;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

public class ChatApdapter extends ArrayAdapter<Chat> {
	// User mUser;
	public ChatApdapter(Context context, List<Chat> list/* , User user */) {
		super(context, R.layout.chat_item_left, list);
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		LayoutInflater inflater = (LayoutInflater) getContext()
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View row;
		if (position == 0) {
			row = inflater.inflate(R.layout.chat_item_left, parent, false);
		} else {
			if (getItem(position).getUser().equals(getItem(position - 1).getUser())) {
				row = getView(position - 1, convertView, parent);
				row.findViewById(R.id.img_avatar).setVisibility(View.INVISIBLE);
				row.findViewById(R.id.tv_username).setVisibility(View.GONE);
			} else {
				View previousView = row = getView(position - 1, convertView, parent);
				if (previousView.findViewById(R.id.layout_chat_left) != null) {
					row = inflater.inflate(R.layout.chat_item_right, parent, false);
				} else {
					row = inflater.inflate(R.layout.chat_item_left, parent, false);
				}
			}
		}
		Chat chat = getItem(position);
		((TextView) row.findViewById(R.id.tv_username)).setText(chat.getUser().getFullName());
		((TextView) row.findViewById(R.id.tv_message)).setText(chat.getMessage());
		((TextView) row.findViewById(R.id.tv_time)).setText(chat.getTime());
		return row;
	}
}
